package com.sunshine.schedulegrid.utils

import com.sunshine.schedulegrid.bean.CourseBean
import com.sunshine.schedulegrid.config.ScheduleConfig

/**
 * 日程实体类列表
 * @author sunshine
 * @date 2020/8/31
 * @see CourseBean
 * @see ICourseList
 */
class CourseList(sc: ScheduleConfig? = null) : ICourseList{

    //日程实体类列表
    private val list: ArrayList<CourseBean> = ArrayList()

    //日程配置对象
    private var scheduleConfig: ScheduleConfig

    //日程显示模式

    //日程列表是否发生变化
    private var listChange = false

    override fun add(courseBean: CourseBean) {
        listChange = true
        list.add(courseBean)
    }

    override fun remove(courseBean: CourseBean) {
        listChange = true
        list.remove(courseBean)
    }

    override fun get(): ArrayList<CourseBean> {
        if (listChange) sort()
        return list
    }

    /**
     * 请注意
     * 排序功能在日程列表发生变化且在调用get方法时会自动调用
     * 无需手动调用
     */
    override fun sort() {
        quickSort(list, 0, list.size - 1)
        listChange = false

    }

    //快排处理
    private fun quickSort(arr: ArrayList<CourseBean>, low: Int, high: Int) {
        var t: CourseBean
        if (low > high) {
            return
        }
        var i: Int = low
        var j: Int = high
        //temp就是基准位
        val temp: Int = quickCalculate(arr[low])
        val tempCB: CourseBean = arr[low]
        while (i < j) {
            //先看右边，依次往左递减
            while (temp >= quickCalculate(arr[j]) && i < j) {
                j--
            }
            //再看左边，依次往右递增
            while (temp <= quickCalculate(arr[i]) && i < j) {
                i++
            }
            //如果满足条件则交换
            if (i < j) {
                t = arr[j]
                arr[j] = arr[i]
                arr[i] = t
            }
        }
        //最后将基准为与i和j相等位置的数字交换
        arr[low] = arr[i]
        arr[i] = tempCB
        //递归调用左半数组
        quickSort(arr, low, j - 1)
        //递归调用右半数组
        quickSort(arr, j + 1, high)
    }

    //快排依据标准
    private fun quickCalculate(courseBean: CourseBean): Int{
        return if (scheduleConfig.scheduleDisplayMode() == ScheduleConfig.LESSON_MODE) courseBean.end - courseBean.start
               else courseBean.endTime - courseBean.startTime
    }

    init {
        scheduleConfig = sc ?: ScheduleConfig()
    }
}